/**
 * Created by zhaocong on 2016/5/25.
 */

// 动画~
window.requestAnimFrame = (function(){
  return  window.requestAnimationFrame   ||
      window.webkitRequestAnimationFrame ||
      window.mozRequestAnimationFrame    ||
      window.oRequestAnimationFrame      ||
      window.msRequestAnimationFrame     ||
      function(/* function */ callback, /* DOMElement */ element){
        window.setTimeout(callback, 1000 / 60);
      };
})();


var imgUrl = 'img/an.jpg';
var positions = ['0,0', '-200,0', '-400,0', '-600,0', '-800,0', '-1000,0', '-1200,0', '-1400,0'];
var ele = document.getElementById('ani');


//animation(ele, positions, imgUrl);
/**
 * 普通的动画
 * @param ele
 * @param positions
 * @param imgUrl
 */
function animation(ele, positions, imgUrl) {
  var i = 0;
  ele.style.backgroundImage = 'url(' + imgUrl + ')';

  function run() {
    var position = positions[i].split(',');
    ele.style.backgroundPosition = position[0] + 'px ' + position[1] + 'px';
    i++;
    if (i >= positions.length) {
      i = 0;
    }
    setTimeout(run, 90);
  }
  run();
}



changePosition(ele, positions, imgUrl, 90);
/**
 * 高能动画
 * @param ele
 * @param positions
 * @param imgUrl
 */
function changePosition(ele,positions,imgUrl,time){
  var i = 0;
  var last;
  ele.style.backgroundImage = 'url(' + imgUrl + ')';

  function run(){
    var position = positions[i].split(',');
    ele.style.backgroundPosition = position[0] + 'px ' + position[1] + 'px';
    i++;
    if(i >= positions.length){
      i = 0;
    }
    last = +new Date();
    timeline();
  }

  function timeline(){
    var now = +new Date();
    if(now-last >= time){
      run();
    }
    requestAnimationFrame(timeline);
  }

  run();
}